package ca.tatham.scheduler.simulate;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

public class TaskDiagram extends Observable {

	private List<TaskLine> m_lines;
	private StringBuilder m_border = new StringBuilder();
	private StringBuilder m_inversion = new StringBuilder();

	TaskDiagram(int numTasks) {
		m_lines = new ArrayList<TaskLine>(numTasks);
	}

	public TaskLine addTask(char c) {
		TaskLine taskLine = new TaskLine(this, c);
		m_lines.add(taskLine);
		return taskLine;
	}

	public String getDiagram() {
		StringWriter writer = new StringWriter();
		BufferedWriter buffer = new BufferedWriter(writer);
		try {
			buffer.append(m_border.toString());
			buffer.newLine();
			for (int i = 0; i < m_lines.size(); i++) {
				buffer.append(m_lines.get(i).getLine());
				buffer.newLine();
			}
			buffer.append(m_inversion.toString());
			buffer.newLine();
			buffer.append(m_border.toString());
			buffer.flush();
		} catch (IOException e) {
			// do nothing
		}

		return writer.toString();
	}

	void unit(TaskLine line) {
		for (TaskLine l : m_lines) {
			if (l != line) {
				l.tick();
			}
		}
		m_border.append('*');
		if (line.getTask().getPriority() != line.getTask()
				.getOriginalPriority()) {
			m_inversion.append('^');
		} else {
			m_inversion.append(' ');
		}
		setChanged();
		notifyObservers();
	}

}
